//
//  PrivateMange.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/5.
//

#import "PrivateMange.h"
#import "NetworkConfig.h"

@interface PrivateMange()
@property (nonatomic ,copy)succuessBlock success;
@end
@implementation PrivateMange

+ (PrivateMange *)share{
    
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

-(BOOL)isLogined
{
    BOOL status = [UserDefaults boolForKey:kIsLogined];
    return status;
}

-(void)saveUserInfo
{
       NSString *dataPath = [NSString stringWithFormat:@"%@/Documents/userData", NSHomeDirectory()];
       
       BOOL result = [NSKeyedArchiver archiveRootObject:self.currentUser toFile:dataPath];
    if(result){
        NSLog(@"----->用户信息归档成功");
    }else{
        NSLog(@"----->归档失败");
    }
    
}


-(BOOL)readUserInfo
{
    NSString *dataPath = [NSString stringWithFormat:@"%@/Documents/userData", NSHomeDirectory()];
    RHUserModel *userModel = [NSKeyedUnarchiver unarchiveObjectWithFile:dataPath];
    self.currentUser = userModel;
    if(userModel){
        NSLog(@"----->解档成功:%@",[userModel yy_modelDescription]);
        return YES;
    }else{
        NSLog(@"----->解档失败");
        return NO;
    }
}

-(void)getUserInfoSuccess:(succuessBlock)success
{
    _success = success;
    kWeakSelf;
    [RHUserModel startGetWithCompletionAPIKey:H_accountInfo argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips hideAllTips];
        if(resultModel.code == 200){
            RHUserModel *user = (RHUserModel*)resultModel.data;
            weakSelf.currentUser = user;
            //归档用户数据
            [weakSelf saveUserInfo];
            
            if (user.brandId > 0) {
                //更新品牌id
                [NetworkConfig sharedConfig].brandID = [NSString stringWithFormat:@"%lld",user.brandId];
                [UserDefaults setObject:[NetworkConfig sharedConfig].brandID forKey:kBrandID];
            }
            
            
            if(weakSelf.success){
                weakSelf.success(user.yy_modelCopy);
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips hideAllTips];
    }];
}
- (void)getAppstoreVersion{
    
    
    
    
    
}
-(RHUserModel *)currentUser
{
    if(!_currentUser){
        _currentUser = [[RHUserModel alloc]init];
        _currentUser.email = @"";
        _currentUser.userName = @"";
        _currentUser.nickName = @"";
        _currentUser.avatar = @"";
    }
    return _currentUser;
}


@end
